// pages/write-story/write-story.js
//使用 async await 语法必须引入，固定写法。
import regeneratorRuntime, { async } from '../../utils/runtime'
const App = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    value: "",
    cursor: 0,
    tempImgPaths: [],//临时图片路径
    fileIDImg: [],
    anonymousAvatar: [
      "cloud://z-201717-dev-9jx1q.7a2d-z-201717-dev-9jx1q-1302077768/anonymous-avatar/nm0.jpg",
      "cloud://z-201717-dev-9jx1q.7a2d-z-201717-dev-9jx1q-1302077768/anonymous-avatar/nm1.jpg",
      "cloud://z-201717-dev-9jx1q.7a2d-z-201717-dev-9jx1q-1302077768/anonymous-avatar/nm2.jpg",
    ],//可选择的匿名头像
    anonymousNickname: [
      "小菠萝",
      "红苹果",
      "黄芒果",
      "青柠檬",
      "酸葡萄",
      "大西瓜",
    ],//可选择的匿名名称
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  //键盘输入事件
  textareaChange(event) {
    const { value, cursor } = event.detail
    this.setData({ value, cursor })

  },
  //选择上传图片
  chooseImg(event) {
    const { id } = event.currentTarget
    if (id === "1") {
      wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: (result) => {
          const tempImgPaths = result.tempFilePaths
          this.setData({ tempImgPaths })
        },
        fail: (res) => { console.log('选择图片失败', res) }
      })
      return
    }
    wx.chooseImage({
      count: 3,
      sizeType: ['original', 'compressed'],
      sourceType: ['album'],
      success: (result) => {
        const tempImgPaths = result.tempFilePaths
        if (tempImgPaths.length !== 3) {
          wx.showToast({
            title: '请一次性选择三张图片',
            icon: 'none',
            duration: 1000,
            mask: false,
          })
          return
        }
        this.setData({ tempImgPaths })
      },
      fail: (res) => { console.log('选择图片失败', res) }
    })
  },
  //清空选择图片
  clearImg() {
    wx.showModal({
      content: '确认清除所有图片?',
      success: (res) => {
        if (res.confirm) {
          this.setData({ tempImgPaths: [] })
        }
      }
    })
  },

  //匿名发表故事
  showToast() {
    wx.showToast({
      title: '发表成功~',
      icon: 'none',
      duration: 1500,
      mask: false,
      success: _ => wx.navigateBack()
    })
  },
  async anonymousSend() {
    let addStoryInfo = {
      avatarUrl: this.data.anonymousAvatar[Math.floor(Math.random() * 4)],
      nickname: this.data.anonymousNickname[Math.floor(Math.random() * 7)],
      create_time: new Date().getTime(),
      fileIDImg:[],
      content: this.data.value,
      count: 0,
      reply_count:0
    }
    // 将图片上传至云存储空间
    const db = wx.cloud.database()
    const tree_hole_story = db.collection("tree_hole_story")
    if (this.data.tempImgPaths.length === 0) {
      await tree_hole_story.add({
        data: addStoryInfo
      })
      this.showToast()
      return
    }
    let fileIDImg = []
    this.data.tempImgPaths.forEach(item => {
      wx.cloud.uploadFile({
        // 指定上传到的云路径
        cloudPath: new Date().getTime().toString(),
        // 指定要上传的文件的小程序临时文件路径
        filePath: item,
        // 成功回调
        success: async res => {
          fileIDImg.push(res.fileID)
          if (fileIDImg.length === this.data.tempImgPaths.length) {
            addStoryInfo.fileIDImg = fileIDImg
            await tree_hole_story.add({
              data: addStoryInfo
            })
            this.showToast()
          }
        }
      })
    })
  },
  //非匿名发表
  async send() {
    const { nickname, avatarUrl } = App.globalData.userInfo
    const addStoryInfo = {
      avatarUrl,
      nickname,
      create_time: new Date().getTime(),
      fileIDImg:[],
      content: this.data.value,
      count: 0,
      reply_count:0
    }
    // 将图片上传至云存储空间
    const db = wx.cloud.database()
    const tree_hole_story = db.collection("tree_hole_story")
    if (this.data.tempImgPaths.length === 0) {
      await tree_hole_story.add({
        data: addStoryInfo
      })
      this.showToast()
      return
    }
    let fileIDImg = []
    this.data.tempImgPaths.forEach(item => {
      wx.cloud.uploadFile({
        // 指定上传到的云路径
        cloudPath: new Date().getTime().toString(),
        // 指定要上传的文件的小程序临时文件路径
        filePath: item,
        // 成功回调
        success: async res => {
          fileIDImg.push(res.fileID)
          if (fileIDImg.length === this.data.tempImgPaths.length) {
            addStoryInfo.fileIDImg = fileIDImg
            await tree_hole_story.add({
              data: addStoryInfo
            })
            this.showToast()
          }
        }
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})